﻿using System.Collections.Generic;
using System.Configuration;
using System.Text;
using NHibernate;
using NHibernate.Cache;

namespace Web7.Core.Domain.NHibernate
{
    public class Web7CacheProvider : ICacheProvider
    {
        private static readonly Dictionary<string, ICache> Caches = new Dictionary<string, ICache>();
        private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(Web7CacheProvider));
        static Web7CacheProvider()
        {
            var section = ConfigurationManager.GetSection("web7cache") as Web7CacheConfig[];
            if (section == null) return;
            foreach (Web7CacheConfig config in section)
            {
                Caches.Add(config.Region, new Web7Cache(config.Region, config.Properties));
            }
        }

        public ICache BuildCache(string regionName, IDictionary<string, string> properties)
        {

            ICache cache;
            if (regionName == null)
            {
                regionName = string.Empty;
            }
            if (Caches.TryGetValue(regionName, out cache))
            {
                return cache;
            }
            if (properties == null)
            {
                properties = new Dictionary<string, string>(1);
            }
            if (Log.IsDebugEnabled)
            {
                var builder = new StringBuilder();
                builder.Append("building cache with region: ").Append(regionName).Append(", properties: ");
                foreach (KeyValuePair<string, string> pair in properties)
                {
                    builder.Append("name=");
                    builder.Append(pair.Key);
                    builder.Append("&value=");
                    builder.Append(pair.Value);
                    builder.Append(";");
                }
                Log.Debug(builder.ToString());
            }
            return new Web7Cache(regionName, properties);
        }

        public long NextTimestamp()
        {
            return Timestamper.Next();
        }

        public void Start(IDictionary<string, string> properties)
        {

        }

        public void Stop()
        {

        }
    }
}
